import { Component, OnInit, ViewChild, ElementRef, SimpleChanges } from '@angular/core';

import { getId } from "utils";
import RenderTreemap from "../../../lib/treemap/render.treemap";

declare var jQuery;

@Component({
  selector: 'draw-treemap',
  templateUrl: 'draw-treemap.component.html',
  styleUrls: ['draw-treemap.component.less'],
  inputs: ['data']
})
export class DrawTreemapComponent implements OnInit {
  @ViewChild('treemap', { read: ElementRef })
  domEl: ElementRef;
  chartId = getId();
  chartIns;
  config;

  constructor() { }

  ngOnInit() { }

  ngOnChanges(changes: SimpleChanges) {
    console.log('%c ngOnChanges is happen', 'color:#f00', changes)
    let svgEl = this.domEl.nativeElement;
    let config = changes.data.currentValue
    let preConfig = changes.data.previousValue
    if (config) {
      this.config = {
        data: config.data,
        clickRectEmitter: config.clickRectEmitter
      }
    }
    if (config && !this.chartIns) {
      this.chartIns = new RenderTreemap(svgEl, this.config);
    } else if (config && this.chartIns) {
      if (preConfig && config.data.name !== preConfig.data.name) {
        this.chartIns = new RenderTreemap(svgEl, this.config);
      } else {
        this.chartIns.update()
      }
    }
  }

  ngOnDestroy () {
    this.chartIns && this.chartIns.destroy()
  }
}